//
//  SubjectDemandServiceTabVC.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/10/29.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import"SubjectDemandServiceTabVC.h"
#import "DemandCell.h"
#import "ServiceCell.h"
#import "HomeModel.h"
#import "ServiceModel.h"
#import "DemandTheHallViewController.h"
#import "ServiceContentTabVC.h"
#import "DemandTheHallContentVC.h"

@interface SubjectDemandServiceTabVC ()<DemandCellDelegate>
@property(nonatomic,strong) NSMutableArray *dataMuta;
@property(nonatomic,strong) HomeModel *homeModel;
@property(nonatomic,assign) NSInteger pageNum;
@property(nonatomic,assign) NSInteger pageSize;
@property(nonatomic,strong) NSDictionary *dict;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) NSString *urlString;
@end
static NSString *identifierNeedContent = @"DemandCell";
static NSString *identifierService = @"ServiceCell";
@implementation SubjectDemandServiceTabVC
-(NSMutableArray *)dataMuta
{
    if (!_dataMuta) {
        _dataMuta = [NSMutableArray array];
    }
    return _dataMuta;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    self.tableView.mj_header = header;
    [header beginRefreshing];
    self.manager = [AFHTTPSessionManager manager];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadMore)];
    self.tableView.mj_footer = footer;
                [footer setTitle:[NSBundle bundleLocalizedStringForKey:@"footerTitle"]
 forState:MJRefreshStateNoMoreData];
                footer.stateLabel.font = [UIFont systemFontOfSize:12];
                footer.stateLabel.textColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1];
    [self.tableView registerNib:[UINib nibWithNibName:@"DemandCell" bundle:nil] forCellReuseIdentifier:identifierNeedContent];
    [self.tableView registerNib:[UINib nibWithNibName:@"ServiceCell" bundle:nil] forCellReuseIdentifier:identifierService];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(associationlistNew:) name:@"associationlistNew" object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectTodayDemand:) name:@"selectTodayDemand" object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(qingqiusibai:) name:@"qingqiusibai" object:nil];
}
-(void)clickRightItem
{
    
}
-(void)refresh
{
    self.dataMuta = nil;
    self.pageNum = 1;
    self.pageSize = 10;
    [self reloadInternetData];
}
-(void)reloadMore
{
    self.pageNum++;
    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
    [WSProgressHUD show];
    [self reloadInternetData];
}
-(void)reloadInternetData
{
    NSString *pageNums = [NSString stringWithFormat:@"%ld",self.pageNum];
    NSString *pageSizes = [NSString stringWithFormat:@"%ld",self.pageSize];
    if (self.indexPath.section == 3) {//最新需求
        self.dict = @{
                      @"pageNum":pageNums,
                      @"pageSize":pageSizes,
                      @"uid":[UserDefaultsHelper readUid],
                      @"token":[UserDefaultsHelper readToken]
                      };
        [CustomeManager POSTWithURLIndex:33 parameters:self.dict success:^(NSDictionary *dict) {
            
        } failure:^(NSError *error) {
            
        }];
    }else {//最新服务
        self.dict = @{
                      @"page":pageNums,
                      @"rows":pageSizes
                      };
        [CustomeManager POSTWithURLIndex:14 parameters:self.dict success:^(NSDictionary *dict) {
            
        } failure:^(NSError *error) {
            
        }];
    }
}
#pragma mark-代理:最新的服务
-(void)associationlistNew:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    NSArray *date = [dict objectForKey:@"date"];
    if (date.count) {
        for (NSDictionary *dict in date) {
            ServiceModel *model = [ServiceModel mj_objectWithKeyValues:dict];
            [self.dataMuta addObject:model];
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
    }else {
        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
    }
    [self.tableView reloadData];
    [WSProgressHUD dismiss];
}
#pragma mark-代理:最新的需求
-(void)selectTodayDemand:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    NSArray *temp = [dict objectForKey:@"date"];
    XLog(@"dict:%@",dict);
    if (temp.count) {
        for (NSDictionary *dict in temp) {
            HomeModel *model =[HomeModel mj_objectWithKeyValues:dict];
            [self.dataMuta addObject:model];
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }else {
        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
    }
    [self.tableView reloadData];
    [WSProgressHUD dismiss];
}
-(void)qingqiusibai:(NSNotification *)info
{
//    [WSProgressHUD dismiss];
    XLog(@"subjectVC");
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataMuta.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    if (self.indexPath.section == 3) {
        DemandCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierNeedContent forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        cell.indexPath = indexPath;
        cell.collectShow = NO;
        HomeModel *homeModel = self.dataMuta[indexPath.row];
        cell.homeModel = homeModel;
        return cell;
        
    }else {
        ServiceCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierService forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (self.dataMuta.count) {
            ServiceModel *model = self.dataMuta[indexPath.row];
            cell.serviceModel = model;
        }
        return cell;
    }
   
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     if (self.indexPath.section == 3) {//最新需求
         DemandTheHallContentVC *demanVC = [[DemandTheHallContentVC alloc]init];
         demanVC.urlString = @"/demand/selectTwoDemand";
         demanVC.homeModel = self.dataMuta[indexPath.row];
         HomeModel *homeModel = self.dataMuta[indexPath.row];
         demanVC.returnValueBlock = ^(NSInteger selected) {
             homeModel.collectStatus = selected;
             [self.tableView reloadData];
         };
         [self.navigationController pushViewController:demanVC animated:YES];
     }else {
         ServiceContentTabVC *homeServiceVC = [[ServiceContentTabVC alloc]init];
         homeServiceVC.model = self.dataMuta[indexPath.row];
         [self.navigationController pushViewController:homeServiceVC animated:YES];
     }
}
#pragma mark-代理:最新需求
-(void)DemandCell:(DemandCell *)DemandCell withClickBtn:(UIButton *)clickBtn withIndexPath:(nonnull NSIndexPath *)indexPath withHomeModel:(nonnull HomeModel *)homeModel
{
    XLog(@"indexPaath.row:%ld",indexPath.row);
    HomeModel *model = self.dataMuta[indexPath.row];
    model.show = clickBtn.selected;
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 144;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 1)];
    return headerView;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 0,1)];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}
#pragma mark-代理:显示联系人
-(void)demandCell:(DemandCell *)demandCell withClickBtn:(UIButton *)clickBtn withIndexPath:(NSIndexPath *)indexPath withHomeModel:(HomeModel *)homeModel
{
    
    if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]) {
        [LogOutAccount presentOutAccount];
        [UIAlertViewWarningAccount showWarningAccount];
    }else if ([UserDefaultsHelper readAutoLogIn].length == 0) {
        [LogOutAccount presentOutAccount];
    }else {
        self.dict = @{
                      @"userId":[UserDefaultsHelper readUid],
                      @"token":[UserDefaultsHelper readToken]
                      };
        self.urlString = [NSString stringWithFormat:@"%@/user/checkToken",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
            if (status == 200) {
                HomeModel *model = self.dataMuta[indexPath.row];
                model.show = clickBtn.selected;
                [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            }else {
                [LogOutAccount presentOutAccount];
                [UIAlertViewWarningAccount showWarningAccount];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
    }
}
#pragma mark-代理:收藏
- (void)demandCell:(DemandCell *)demandCell withCollectBtn:(UIButton *)clickBtn withIndexPath:(NSIndexPath *)indexPath withHomeModel:(HomeModel *)homeModel
{
    
    NSString *ids = [NSString stringWithFormat:@"%ld",homeModel.id];
    NSString *statuS = [NSString stringWithFormat:@"%d",clickBtn.selected];
    //    NSString *type = [NSString stringWithFormat:@"%ld",(long)self.homeModel.type];
    
    if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]) {
        [LogOutAccount presentOutAccount];
        [UIAlertViewWarningAccount showWarningAccount];
    }else if ([UserDefaultsHelper readAutoLogIn].length == 0) {
        [LogOutAccount presentOutAccount];
    }else {
        self.dict = @{
                      @"userId":[UserDefaultsHelper readUid],
                      @"token":[UserDefaultsHelper readToken]
                      };
        self.urlString = [NSString stringWithFormat:@"%@/user/checkToken",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
            if (status == 200) {
                clickBtn.selected = !clickBtn.selected;
                self.dict = @{
                              @"uid":[UserDefaultsHelper readUid],
                              @"id":ids,
                              @"type":@"4",
                              @"status":statuS,
                              @"token":[UserDefaultsHelper readToken]
                              };
                XLog(@"self.dict:%@",self.dict);
                self.urlString = [NSString stringWithFormat:@"%@/collection/insertCollection",kUrl];
                [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    XLog(@"responseObject:%@",responseObject);
                    NSString *message = [responseObject objectForKey:@"message"];
                    [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
                    __weak typeof (self)weakSelf = self;
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                        if (weakSelf.returnValueBlock) {
//                            weakSelf.returnValueBlock(collectBtn.selected);
//                        };
                        [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    });
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    
                }];
            }else {
                [LogOutAccount presentOutAccount];
                [UIAlertViewWarningAccount showWarningAccount];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
    }
    
}
@end
